package socket.chat;

import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.net.Socket;
import java.net.SocketException;
import java.util.Set;

public class Receiver extends Thread {
	private Socket socket;
	private Set<Socket> cs;

	public Receiver(Socket socket, Set<Socket> cs) {
		this.socket = socket;
		this.cs = cs;
	}

	@Override
	public void run() {
		try {
			ObjectInputStream in = new ObjectInputStream(socket.getInputStream());			
			while (true) {				
				Object message = in.readObject();//获取输入数据
				for (Socket sk : cs) {
					ObjectOutputStream out;
					out = new ObjectOutputStream(sk.getOutputStream());					
					Object[] list1={socket.getInetAddress().getHostAddress(),(String)"上线了"};
					out.writeObject(list1);
					out.flush();//清除缓存
				}
				for (Socket sk : cs) {
					ObjectOutputStream out;
					out = new ObjectOutputStream(sk.getOutputStream());					
					Object[] ob={socket.getInetAddress().getHostAddress(),message};					
					out.writeObject(ob);
					out.flush();//清除缓存
				}
			}
		} catch (SocketException e) {
			System.out.println(socket.getInetAddress().getHostAddress()+"下线了");
			cs.remove(socket);
			for (Socket sk : cs) {
				ObjectOutputStream out;
				try {
					out = new ObjectOutputStream(sk.getOutputStream());					
					Object[] list2={socket.getInetAddress().getHostAddress(),(String)"下线了"};
					out.writeObject(list2);
					out.flush();//清除缓存
				} catch (IOException e1) {
					// TODO Auto-generated catch block
					e1.printStackTrace();
				}
			}
		} catch (ClassNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
}
